<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="车间任务卡编号" prop="sn" label-width="55">
        <el-input
          v-model="queryParams.sn"
          placeholder="请输入车间任务卡编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="primary"-->
      <!--          plain-->
      <!--          icon="el-icon-plus"-->
      <!--          size="mini"-->
      <!--          @click="handleAdd"-->
      <!--          v-hasPermi="['mes:card:add']"-->
      <!--        >新增</el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="success"-->
      <!--          plain-->
      <!--          icon="el-icon-edit"-->
      <!--          size="mini"-->
      <!--          :disabled="single"-->
      <!--          @click="handleUpdate"-->
      <!--          v-hasPermi="['mes:card:edit']"-->
      <!--        >修改</el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="danger"-->
      <!--          plain-->
      <!--          icon="el-icon-delete"-->
      <!--          size="mini"-->
      <!--          :disabled="multiple"-->
      <!--          @click="handleDelete"-->
      <!--          v-hasPermi="['mes:card:remove']"-->
      <!--        >删除</el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['mes:card:export']"
        >导出</el-button>
      </el-col>
      <!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
    </el-row>

    <el-table v-loading="loading" :data="cardList" border style="width: 100%" @selection-change="handleSelectionChange">
      <!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="序号" align="center" prop="number" width="80"/>
      <el-table-column label="任务卡状态" align="center" prop="taskState" width="90" >
        <template v-slot = "scope">
          <dict-tag :options="dict.type.card_status" :value="scope.row.taskState"/>
        </template>
      </el-table-column>
      <!--      <el-table-column label="车间任务卡id" align="center" prop="id" />-->
      <el-table-column label="生产进度" align="center" width="140">
        <template v-slot="{ row }">
          <div class="demo-progress">
            <el-progress :text-inside="true" :stroke-width="15" :percentage="calculateProgressPercentage(row.planNum, row.proNum)" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="车间任务编号" align="center" prop="sptkSn" width="150"/>
      <el-table-column label="任务卡编号" align="center" prop="sn" width="180"/>
      <!--      <el-table-column label="车间任务id" align="center" prop="sptkId" />-->
      <el-table-column label="产品名称" align="center" prop="proName" width="120"/>
      <el-table-column label="产品编码" align="center" prop="proSn" width="150"/>
      <el-table-column label="生产批号" align="center" prop="proLotNumber" width="150" />
      <el-table-column label="计划生产数量" align="center" prop="planNum" width="120"/>
      <el-table-column label="已生产数量" align="center" prop="proNum" width="120"/>
      <el-table-column label="计划开始日期" align="center" prop="planStartDate" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planStartDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划完成时间" align="center" prop="planEndDate" width="130">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planEndDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createdBy" />
      <el-table-column label="创建时间" align="center" prop="createdTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="备注" align="center" prop="remark" />-->
      <el-table-column label="操作" align="center" fixed="right" width="130">
        <template slot-scope="scope">
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-edit"-->
          <!--            @click="handleUpdate(scope.row)"-->
          <!--            v-hasPermi="['mes:card:edit']"-->
          <!--          >修改</el-button>-->
          <el-button
            size="20"
            type="text"
            icon="el-icon-check"
            @click="handleSigning(scope.row,scope.$index)"
          >执行工序</el-button>
          <el-dropdown>
              <span class="el-dropdown-link">
                <el-icon class="el-icon-more">
                  </el-icon>
                  更多
                </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-check"
                    @click="handleSetQuality(scope.$index)"
                  >质检&报工</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                  >撤销任务卡</el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改车间任务卡对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="车间任务卡编号" prop="sn" >
          <el-input v-model="form.sn" placeholder="请输入车间任务卡编号"/>
        </el-form-item>
        <el-form-item label="生产批号" prop="proLotNumber">
          <el-input v-model="form.proLotNumber" placeholder="请输入生产批号" />
        </el-form-item>
        <el-form-item label="任务卡状态" prop="taskState">
          <el-input v-model="form.taskState" placeholder="请输入任务卡状态" />
        </el-form-item>
        <el-form-item label="计划生产数量" prop="planNum">
          <el-input v-model="form.planNum" placeholder="请输入计划生产数量" />
        </el-form-item>
        <el-form-item label="已生产数量" prop="proNum">
          <el-input v-model="form.proNum" placeholder="请输入已生产数量" />
        </el-form-item>
        <el-form-item label="计划开始日期" prop="planStartDate">
          <el-date-picker clearable
                          v-model="form.planStartDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择计划开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="计划完成时间" prop="planEndDate">
          <el-date-picker clearable
                          v-model="form.planEndDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择计划完成时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 报工对话框 -->
    <el-dialog :title="titleSigning" :visible.sync="openSigning" width="1010px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-divider>工序列表</el-divider><!--分割线-->
        <el-card shadow="always" style="border-radius: 15px;">
          <el-table border style="width: 100%" v-loading="loading" :data="formSigningList">
            <el-table-column label="产品编码" align="center" width="240">
              <template slot-scope="scope" >
                <span>{{scope.row.proName+"/"+scope.row.proSn}}</span>
              </template>
            </el-table-column>
            <el-table-column label="任务卡编号" prop="sn" align="center" width="100">
              <template slot-scope="scope" >
                <span>{{scope.row.sn}}</span>
              </template>
            </el-table-column>
            <el-table-column label="工序" prop="pcsName" align="center" width="140">
              <template slot-scope="scope">
                  <el-tag :type="getProcessStatusType(scope.row.pcsName)"
                          style="color: #575757; cursor: pointer"
                          :loading="isDeviceLoading(scope.row.pcsName)"
                          @click="handlePcsName(scope.row.pcsName)">
                  {{ scope.row.pcsName }}
                    <span v-if="getDeviceStatus(scope.row.pcsName)">
                    ({{ getDeviceStatusText(scope.row.pcsName) }})
                  </span>
                 </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="绑定设备" prop="eptName" align="center" width="120">
              <template slot-scope="scope" >
                <span>{{scope.row.eptName}}</span>
              </template>
            </el-table-column>
            <el-table-column label="计划执行次数" prop="planNum" align="center" width="110">
              <template slot-scope="scope" >
                <span>{{scope.row.planNum}}</span>
              </template>
            </el-table-column>
            <el-table-column label="生产报工数量" prop="sigNum" align="center" width="210">
              <template slot-scope="scope" >

                <el-input-number v-model="scope.row.sigNum" placeholder="请输入生产报工数量" :min="0" :max="scope.row.planNum" controls :step="1" />
              </template>
            </el-table-column>

          </el-table>
        </el-card>

      </el-form>
      <!-- 设备状态面板 -->
      <el-divider>设备状态</el-divider>
      <div class="device-status-panel">
        <div v-for="device in deviceStatusList" :key="device.id" class="device-card">
          <div class="device-name">{{ device.name }}</div>
          <div :class="['status-indicator', device.statusClass]">
            {{ device.statusText }}
          </div>
        </div>
      </div>

      <!-- 一键报工进度显示 -->
      <el-divider>一键报工进度</el-divider>
      <div class="batch-progress">
        <el-steps :active="currentStep" align-center>
          <el-step
            v-for="(step, index) in processSequence"
            :key="index"
            :title="step.name"
            :status="getStepStatus(index)"
          />
        </el-steps>
        <div class="progress-info">
          <el-tag :type="progressStatusType" size="medium">
            {{ progressMessage }}
          </el-tag>
          <el-button
            v-if="isBatchRunning && currentStep < processSequence.length"
            type="danger"
            size="small"
            @click="cancelBatch"
            style="margin-left: 15px;"
          >
            取消报工
          </el-button>
          <el-progress
            :percentage="progressPercentage"
            :status="progressStatus"
            :stroke-width="18"
            style="margin-top: 20px;"
          />
        </div>
      </div>


      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="oneReport"
          :loading="batchLoading"
        >
          一键报工
        </el-button>
        <el-button type="primary" @click="submitFormSigning">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 质检对话框 -->
    <el-dialog :title="titleQuality" :visible.sync="openQuality" width="500px" append-to-body>
      <el-form ref="form" :model="formQuality" :rules="rules" label-width="120px">
        <el-form-item label="待质检数量:"  >
          {{formQuality.productionNum}}
        </el-form-item>
        <el-form-item label="质检数量" >
          <el-input-number v-model="formQuality.qualityNum" placeholder="请输入质检数量" :min="0" :max="formQuality.productionNum" controls :step="1" />
        </el-form-item>
        <el-form-item label="可报工数量:" >
          <span>{{this.form.signNum}}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handlePcsName('质检',formQuality.qualityNum)">质检</el-button>
        <el-button type="primary" @click="submitFormQuality">报 工</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


  </div>

</template>

<script>
import { listCard, getCard, delCard, addCard, updateCard, getCardProcess} from "@/api/mes/card";
import Vue from "vue";
import {AgvCarService, FourRobotArm, GantryService, MarkingMachine, SixRobotArm} from "@/api/equipmentAPI/equipmentAPI";
// import {sendDeviceCommand} from "../../../api/equipmentAPI/device";
import webSocketService from '../../../api/equipmentAPI/websocket';
// 工序到设备的映射
const PROCESS_TO_DEVICE = {
  '六轴取料': { id: 'sixArm', name: '六轴取料机' },
  '攻丝机打螺丝': { id: 'fourArm', name: '攻丝机' },
  '质检': { id: 'inspection', name: '质检设备' },
  'log打标': { id: 'marking', name: '打标机' },
  '四轴打包到仓库': { id: 'threeArm', name: '四轴打包机' }
};
// 工序执行顺序
const PROCESS_SEQUENCE = [
  { name: '六轴取料', device: 'sixArm', command: 'start' },
  { name: '攻丝机打螺丝', device: 'fourArm', command: 'start' },
  { name: '质检', device: 'inspection', command: 'start' },
  { name: 'log打标', device: 'marking', command: 'start' },
  { name: '四轴打包到仓库', device: 'threeArm', command: 'start' }
];
export default {
  name: "Card",
  dicts:["card_status"],
  data() {
    return {
      //报工和质检行数
      Index:0,
      //存放已报工数量和质检通过数量
      QualityNumList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 车间任务卡表格数据
      cardList: [],
      // 弹出层标题
      title: "",
      titleQuality:"",
      titleSigning:"",
      // 是否显示弹出层
      open: false,
      openQuality:false,
      openSigning:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sn: null,
      },
      // 表单参数
      form: {},
      formQuality: {
        qualityNum:0,
      },
      formSigningList:[
      ],
      // 表单校验
      rules: {
      },
      // 设备状态存储
      deviceStatuses: {
        sixArm: { status: 0, loading: false }, // 0:在线, finish:完成
        fourArm: { status: 0, loading: false },
        inspection: { status: 0, loading: false },
        marking: { status: 0, loading: false },
        threeArm: { status: 0, loading: false }
      },
      // 一键报工相关状态
      batchLoading: false,
      isBatchRunning: false,
      batchCanceled: false,
      currentStep: 0,
      progressPercentage: 0,
      progressStatus: 'success',
      progressMessage: '准备开始一键报工',
      processSequence: PROCESS_SEQUENCE,
      processStatus: {}, // 存储每个工序的状态
      statusListeners: {} // 存储每个设备的监听器
    };
  },
  created() {
    this.getList();
  },
  computed: {
    progressStatusType() {
      switch (this.progressStatus) {
        case 'success': return 'success';
        case 'exception': return 'danger';
        case 'warning': return 'warning';
        default: return 'info';
      }
    },
    // 设备状态列表用于显示
    deviceStatusList1() {
      return Object.entries(PROCESS_SEQUENCE).map(([index, step]) => {
        const device = step.device;
        const status = this.deviceStatuses[device].status;
        let statusText, statusClass;

        if (status === 200) {
          statusText = '已完成';
          statusClass = 'completed';
        } else if (status === 100) {
          statusText = '执行中';
          statusClass = 'running';
        } else {
          statusText = '待执行';
          statusClass = 'idle';
        }

        return {
          id: device,
          name: step.name,
          statusText,
          statusClass
        };
      });
    },
    // 设备状态列表用于显示
    deviceStatusList() {
      return Object.entries(PROCESS_TO_DEVICE).map(([process, device]) => {
        const status = this.deviceStatuses[device.id].status;
        let statusText, statusClass;

        if (status === 0) {
          statusText = '在线';
          statusClass = 'online';
        } else if (status === 100) {
          statusText = '运行中';
          statusClass = 'running';
        } else if(status==="finish"){
          statusText = '完成';
          statusClass = 'finishing';
        }
        return {
          id: device.id,
          name: device.name,
          statusText,
          statusClass
        };
      });
    }
  },
  mounted() {
    // 初始化WebSocket连接
    webSocketService.connect();

    // 订阅设备状态更新
    webSocketService.subscribe('/topic/device/status', this.handleDeviceStatusUpdate);
  },
  methods: {
    async oneReport() {
      this.batchLoading = true;
      this.isBatchRunning = true;
      this.batchCanceled = false;
      this.currentStep = 0;
      this.progressPercentage = 0;
      this.progressStatus = 'success';
      this.progressMessage = '开始执行一键报工...';

      // 初始化工序状态
      this.processSequence.forEach(step => {
        this.$set(this.processStatus, step.name, '待执行');
      });
      try {
        // 按顺序执行每个工序
        for (let i = 0; i < this.processSequence.length; i++) {
          if (this.batchCanceled) break;

          const step = this.processSequence[i];
          this.currentStep = i + 1;
          this.progressPercentage = Math.floor((i + 1) / this.processSequence.length * 100);
          this.progressMessage = `正在执行: ${step.name}...`;
          this.$set(this.processStatus, step.name, '执行中');
          try {
            // 发送设备命令并等待完成
            await this.executeDeviceCommand(step.device, step.command);

            // 更新工序状态为"已完成"
            this.$set(this.processStatus, step.name, '已完成');
            this.progressMessage = `${step.name} 完成`;
          } catch (error) {
            this.progressStatus = 'exception';
            this.$set(this.processStatus, step.name, '失败');
            this.progressMessage = `${step.name} 执行失败: ${error.message}`;
            this.$message.error(`${step.name} 执行失败`);
            break;
          }
          if (this.batchCanceled) {
            this.progressStatus = 'warning';
            this.progressMessage = '报工已取消';
            this.$message.warning('一键报工已取消');
          } else if (this.progressStatus !== 'exception') {
            this.progressMessage = '所有工序已完成';
            this.$message.success('一键报工完成');
          }
        }
      }
       catch (error){
        this.progressStatus = 'exception';
        this.progressMessage = `报工失败: ${error.message}`;
        this.$message.error(`一键报工失败: ${error.message}`);
        }
      finally{
        // 清理所有监听器
        Object.values(this.statusListeners).forEach(listener => {
          webSocketService.unsubscribe('/topic/device/status', listener);
        });
        this.statusListeners = {};

        this.batchLoading = false;
        this.isBatchRunning = false;
      }
    },

    // 取消一键报工
    cancelBatch() {
      this.batchCanceled = true;
      this.isBatchRunning = false;
      this.progressStatus = 'warning';
      this.progressMessage = '正在取消报工...';
    },
    getStepStatus(index) {
      if (this.batchCanceled && index >= this.currentStep - 1) {
        return 'warning';
      }

      if (index < this.currentStep - 1) return 'success';
      if (index === this.currentStep - 1) {
        return this.progressStatus === 'exception' ? 'error' : 'process';
      }
      return 'wait';
    },
    // 获取工序状态
    getProcessStatus(pcsName) {
      return this.processStatus[pcsName] || '未开始';
    },
    // 获取工序状态标签类型
    getProcessStatusType(pcsName) {
      const status = this.getProcessStatus(pcsName);
      switch (status) {
        case '已完成': return 'success';
        case '执行中': return 'warning';
        case '失败': return 'danger';
        default: return 'info';
      }
    },

    // 执行设备命令并等待完成
    executeDeviceCommand(device, command) {
      return new Promise((resolve, reject) => {
        // 发送设备命令
        webSocketService.sendControlCommand(device, command);
        // 设置超时（30秒）
        const timeout = setTimeout(() => {
          reject(new Error('设备响应超时'));
        }, 30000);

          // 创建状态监听器
          const listener = (status) => {
            if (status.device === device) {
              if (status.status === 'finish') {
                // 设备完成操作
                clearTimeout(timeout);
                webSocketService.unsubscribe('/topic/device/status', listener);
                delete this.statusListeners[device];
                resolve();
              }
            }
          }
        // 注册监听器
        this.statusListeners[device] = listener;
        webSocketService.subscribe('/topic/device/status', listener);

      });
    },
    //报工
    handleSigning(row,index){
      this.Index=index;
      const proId = row.proId;
      getCardProcess(proId).then(response=>{
        this.formSigningList = response.rows
        this.formSigningList.forEach((item,index)=>{
          item.planNum=row.planNum-row.proNum;
          item.sn = row.sn;
          item.proName=row.proName;
          item.proSn=row.proSn;
        })
        this.openSigning=true;
        this.titleSigning="执行工序";
      })
    },
    handlePcsName(pcsName) {
      // 工序名称到设备命令的映射
      const commandMap = {
        '六轴取料': {device: 'sixArm', command: 'start'},
        '攻丝机打螺丝': {device: 'fourArm', command: 'start'},
        '质检': {device: 'inspection', command: 'start'},
        'log打标': {device: 'marking', command: 'start'},
        '四轴打包到仓库': {device: 'threeArm', command: 'start'}
      }

      const commandInfo = commandMap[pcsName]
      if (!commandInfo) {
        return Promise.reject(new Error(`未知的工序名称: ${pcsName}`))
      }
      this.$set(this.deviceStatuses[commandInfo.device], 'loading', true);
      webSocketService.sendControlCommand(commandInfo.device, commandInfo.command)
      this.$set(this.deviceStatuses[commandInfo.device], 'status', 100);
    },
    // 处理设备状态更新
    handleDeviceStatusUpdate(status) {
      console.log(status)
      if (status.device) {
        // 更新设备状态
        this.$set(this.deviceStatuses[status.device], 'status', status.status);

        // 重置加载状态
        this.$set(this.deviceStatuses[status.device], 'loading', false);

        // 显示通知
        this.$notify({
          title: `${this.getDeviceName(status.device)} 状态更新`,
          message: `当前状态: ${status.status === 'finish' ? '完成' : '在线'}`,
          type: status.status === 'finish' ? 'success' : 'warning'
        });
      }
    },
    // 获取设备名称
    getDeviceName(deviceId) {
      for (const [process, device] of Object.entries(PROCESS_TO_DEVICE)) {
        if (device.id === deviceId) {
          return device.name;
        }
      }
      return deviceId;
    },
    // 获取设备状态文本
    getDeviceStatusText(pcsName) {
      const deviceInfo = PROCESS_TO_DEVICE[pcsName];
      if (deviceInfo) {
        const status = this.deviceStatuses[deviceInfo.id].status;
        return status === 'finish' ? '完成' : '运行中';
      }
      return '';
    },
    // 获取设备状态
    getDeviceStatus(pcsName) {
      const deviceInfo = PROCESS_TO_DEVICE[pcsName];
      if (deviceInfo) {
        return this.deviceStatuses[deviceInfo.id].status;
      }
      return 0;
    },
    // 检查设备是否正在加载
    isDeviceLoading(pcsName) {
      const deviceInfo = PROCESS_TO_DEVICE[pcsName];
      if (deviceInfo) {
        return this.deviceStatuses[deviceInfo.id].loading;
      }
      return false;
    },
    //质检
    handleSetQuality(index){
      this.formQuality.productionNum=this.QualityNumList[index].sigNum;
      this.Index=index;
      this.openQuality=true;
      Vue.set(this.form, 'signNum', 0);
      this.titleQuality="质检&报工";
    },
    /** 查询车间任务卡列表 */
    getList() {
      this.loading = true;
      listCard(this.queryParams).then(response => {
        this.cardList = response.rows;
        this.cardList.forEach((item, index) => {
          Vue.set(this.QualityNumList, index, {sigNum:0,passQualityNum:0});
        });
        this.total = response.total;
        this.loading = false;
        this.calculateIndex()
      });
    },
    /** 计算列表编号 */
    calculateIndex() {
      this.cardList.forEach((item, index) => {
        this.$set(item, 'number', index + 1);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openQuality=false;
      this.openSigning=false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sn: null,
        sptkId: null,
        proLotNumber: null,
        taskState: null,
        planNum: null,
        proNum: null,
        planStartDate: null,
        planEndDate: null,
        isDeleted: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedDate: null,
        signNum:0,
        remark: null
      };
      this.resetForm("form");
    },
    //根据计划生产数量和已生产数量计算生产进度的比值
    calculateProgressPercentage(planNum, gbtNum) {
      // 确保计划生产数量和已生产数量都是数字
      if (isNaN(planNum) || isNaN(gbtNum)) {
        return 0;
      }
      if (planNum === 0) {
        // 避免除以零的情况
        return 0;
      }
      // 计算百分比并四舍五入
      return Math.round((gbtNum / planNum) * 100);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },





    // async handlePcsName(pcsName,qualityNum) {
    //   // 定义一个映射，将pcsName与对应的请求方法关联起来
    //   const requestMap = {
    //     '三轴龙门取料': () => GantryService.materialOutbound(),
    //     'AGV小车移动1': () => AgvCarService.advanceToNextStop(),
    //     '六轴取料': () => SixRobotArm.fetchFromCar(),
    //     '打标机打标': () => MarkingMachine.printImage(),
    //     '六轴放料': () => SixRobotArm.placeToCar(),
    //     'AGV小车移动2': () => AgvCarService.advanceToNextStop(),
    //     '质检': () => FourRobotArm.qualityCheck(),
    //     '三轴龙门放料': () => GantryService.materialInbound(),
    //     '合格品入库': () => GantryService.qualifiedInbound(),
    //     '不合格品入库': () => GantryService.nonQualifiedInbound(),
    //     '返回初始位置': () => AgvCarService.returnToHomeStop(),
    //     // 添加更多的工序和对应的方法
    //   };
    //   // 获取对应的请求方法
    //   const requestMethod = requestMap[pcsName];
    //   // 添加日志以确认requestMethod的值
    //   console.log("pcsName", pcsName);
    //   console.log("requestMethod", requestMethod);
    //
    //   if (requestMethod && typeof requestMethod === 'function') {
    //     try {
    //       const timeoutPromise = new Promise((_, reject) => {
    //         setTimeout(() => {
    //           reject(new Error('请求超时'));
    //         }, 2000);
    //       });
    //
    //       const response = await Promise.race([
    //         requestMethod(),
    //         timeoutPromise
    //       ]);
    //       if (response.status === 200) {
    //         this.$modal.msgSuccess("设备调用成功");
    //         if(qualityNum != null){
    //           this.$modal.alertSuccess("质检成功，已成功生产数量：" + qualityNum );
    //           Vue.set(this.form, 'signNum', qualityNum);
    //         }
    //       } else {
    //         this.$modal.msgError("设备调用失败");
    //       }
    //     } catch (error) {
    //       this.$modal.msgWarning("设备未在线");
    //     }
    //   } else {
    //     // 如果requestMethod不存在或不是函数，则提示设备未启用
    //     this.$modal.msgError("设备未启用");
    //   }
    // },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加车间任务卡";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCard(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改车间任务卡";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.cardList[this.Index].proNum=this.formQuality.qualityNum;
      if( this.cardList[this.Index].proNum< this.cardList[this.Index].planNum)
      {
        this.cardList[this.Index].taskState=0;
      }
      else {
        this.cardList[this.Index].taskState=1;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCard(this.cardList[this.Index]).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCard(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    submitFormSigning(){
      var min = 0;
      this.formSigningList.forEach((item, index) => {
        if(index==0){
          min = item.sigNum;
        }
        else{
          if(min>item.sigNum){
            min = item.sigNum;
          }
        }
      });
      this.QualityNumList[this.Index].sigNum=min;
      this.openSigning=false;
      this.$modal.alertSuccess("工序完成，请质检！")
      console.log("this.signingList[this.qualityIndex]",this.QualityNumList[this.Index])
    },
    submitFormQuality(){
      this.QualityNumList[this.Index].passQualityNum=this.formQuality.qualityNum;
      this.cardList[this.Index].proNum=this.form.signNum;
      if( this.cardList[this.Index].proNum< this.cardList[this.Index].planNum)
      {
        this.cardList[this.Index].taskState=0;
      }
      else {
        this.cardList[this.Index].taskState=1;
      }
      console.log("this.cardList[this.Index]",this.cardList[this.Index])
      updateCard(this.cardList[this.Index]).then(response => {
        this.$modal.msgSuccess("报工完成");
        this.form.signNum=0;
        this.openQuality=false;
        this.getList();
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除车间任务卡编号为"' + ids + '"的数据项？').then(function() {
        return delCard(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/card/export', {
        ...this.queryParams
      }, `card_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style>
.device-status-panel {
  display: flex;
  flex-wrap: wrap;
  gap: 20px; /* Adjust spacing between cards */
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  margin-top: 20px;
}

.device-card {
  flex: 1 1 calc(33% - 20px); /* Adjust card width and spacing */
  box-sizing: border-box;
  border: 1px solid #e0e0e0;
  padding: 15px;
  border-radius: 10px;
  text-align: center;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  background-color: #fff;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
}

.device-name {
  font-size: 1.1em;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
}

.status-indicator {
  padding: 8px 15px;
  border-radius: 20px;
  text-align: center;
  color: white;
  font-weight: bold;
  font-size: 14px;
  min-width: 80px;
}

.status-indicator.running {
  background-color: #fb0000;
}

.status-indicator.online {
  background-color: #67c23a;
}

.status-indicator.finishing {
  background-color: #2265ef;
}

.el-button.is-loading:before {
  background-color: transparent;
}
</style>
